<template>
  <view class="edit-page bucket-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="存储配置" name="configId" required>
          <BottomSelect
              v-model="form.configId"
              :options="storageOptions"
              value-field="configId"
              label-field="configName"
              placeholder="请选择存储配置"
              title="选择存储配置"
              :disabled="mode === 'view' || mode === 'edit'"/>
          <view class="config-info" v-if="currentConfig">
            <view class="info-item">
              <text class="info-label">类型：</text>
              <text class="info-value">{{ getStorageTypeName(currentConfig.storageType) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">地址：</text>
              <text class="info-value">{{ currentConfig.endpoint || '本地存储' }}</text>
            </view>
          </view>
        </uni-forms-item>

        <uni-forms-item label="桶名称" name="bucketName" required>
          <uni-easyinput
              v-model="form.bucketName"
              :placeholder="getBucketNamePlaceholder()"
              :disabled="mode === 'view' || mode === 'edit'"
              :clearable="mode === 'add'">
          </uni-easyinput>
          <text class="form-tip">{{ getBucketNameTip() }}</text>
        </uni-forms-item>

        <uni-forms-item label="访问权限" name="permission" v-if="currentConfig?.storageType !== 'local'">
          <BottomSelect
              v-model="form.permission"
              :options="permissionOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择访问权限"
              title="选择访问权限"
              :disabled="mode === 'view'"/>

          <view class="permission-tips">
            <view class="tip-item">
              <text class="tip-label">私有：</text>
              <text class="tip-text">只有桶拥有者可以访问</text>
            </view>
            <view class="tip-item">
              <text class="tip-label">公共读：</text>
              <text class="tip-text">任何人都可以读取桶中的文件</text>
            </view>
            <view class="tip-item">
              <text class="tip-label">公共读写：</text>
              <text class="tip-text">任何人都可以读取和写入桶中的文件</text>
            </view>
          </view>
        </uni-forms-item>

        <!-- 本地存储说明 -->
        <view class="local-storage-info" v-if="currentConfig?.storageType === 'local'">
          <uni-icons type="info" size="16" color="#007aff"></uni-icons>
          <text class="info-text">本地存储不支持权限配置，所有文件默认为私有访问。</text>
        </view>

        <uni-forms-item label="设为默认桶" name="isDefault" v-if="mode !== 'add'">
          <switch
              :checked="form.isDefault === 1"
              @change="handleDefaultChange"
              :disabled="mode === 'view'"/>
          <text class="form-tip">设置为当前存储配置的默认存储桶</text>
        </uni-forms-item>

        <!-- 桶信息（仅查看和编辑模式） -->
        <view class="bucket-info" v-if="mode !== 'add'">
          <view class="info-row">
            <text class="info-label">桶名称：</text>
            <text class="info-value">{{ form.bucketName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">存储类型：</text>
            <text class="info-value">{{ getStorageTypeName(currentConfig?.storageType) }}</text>
          </view>
          <view class="info-row" v-if="currentConfig?.endpoint">
            <text class="info-label">访问地址：</text>
            <text class="info-value">{{ currentConfig.endpoint }}</text>
          </view>
          <view class="info-row" v-if="currentConfig?.region">
            <text class="info-label">区域：</text>
            <text class="info-value">{{ currentConfig.region }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">自定义域名：</text>
            <text class="info-value">{{ currentConfig?.domain || '未配置' }}</text>
          </view>
        </view>

      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions" v-if="mode !== 'view'">
      <view class="action-buttons">
        <view class="cancel-btn" @click="handleCancel">取消</view>
        <view class="submit-btn" @click="handleSubmit">
          {{ mode === 'add' ? '确认创建' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {createBucket, setBucketPermission} from '@/api/filemanager/bucket'
import {getStorageConfig, listStorageConfig, updateStorageConfig} from '@/api/filemanager/storage'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()

// 页面参数
const mode = ref('add') // add, edit, view
const bucketName = ref('')
const configId = ref(null)
const formRef = ref()

// 存储配置选项
const storageOptions = ref([])
const currentConfig = computed(() => {
  return storageOptions.value.find(item => item.configId === form.configId)
})

// 表单数据
const form = reactive({
  configId: undefined,
  bucketName: '',
  permission: 'private',
  isDefault: 0
})

// 权限选项
const permissionOptions = [
  {value: 'private', text: '私有'},
  {value: 'public-read', text: '公共读'},
  {value: 'public-read-write', text: '公共读写'}
]

// 表单验证规则
const rules = reactive({
  configId: {
    rules: [{required: true, errorMessage: '请选择存储配置'}]
  },
  bucketName: {
    rules: [{required: true, errorMessage: '请输入桶名称'}]
  }
})

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  mode.value = options.mode || 'add'
  bucketName.value = options.bucketName || ''
  configId.value = options.configId

  // 设置页面标题
  const titleMap = {
    add: '创建存储桶',
    edit: '编辑存储桶',
    view: '查看存储桶'
  }
  uni.setNavigationBarTitle({
    title: titleMap[mode.value]
  })
})

// 页面加载
onMounted(() => {
  loadStorageOptions()
})

// 加载存储配置选项
async function loadStorageOptions() {
  try {
    const response = await listStorageConfig({pageNum: 1, pageSize: 100})
    if (response.code === 200) {
      storageOptions.value = response.rows || []

      // 设置默认选择的配置
      if (configId.value) {
        form.configId = parseInt(configId.value)
      } else if (storageOptions.value.length > 0) {
        const defaultConfig = storageOptions.value.find(item => item.isDefault === 1) || storageOptions.value[0]
        form.configId = defaultConfig.configId
      }

      // 如果是编辑或查看模式，设置桶名称
      if (mode.value !== 'add' && bucketName.value) {
        form.bucketName = bucketName.value
        loadBucketInfo()
      }
    }
  } catch (error) {
    console.error('加载存储配置失败:', error)
  }
}

// 加载存储桶信息（编辑和查看模式）
async function loadBucketInfo() {
  // 这里可以调用API获取存储桶的详细信息
  // 暂时使用基本信息
  form.permission = 'private'
  form.isDefault = 0
}

// 获取存储类型名称
function getStorageTypeName(type) {
  const typeMap = {
    'local': '本地存储',
    'minio': 'MinIO',
    'aliyun': '阿里云OSS',
    'tencent': '腾讯云COS',
    'aws': 'AWS S3'
  }
  return typeMap[type] || type
}

// 获取桶名称占位符
function getBucketNamePlaceholder() {
  const selectedConfig = currentConfig.value
  if (selectedConfig?.storageType === 'local') {
    return '请输入目录名称（如：images、documents）'
  }
  return '请输入存储桶名称（小写字母、数字、连字符）'
}

// 获取桶名称提示信息
function getBucketNameTip() {
  const selectedConfig = currentConfig.value
  if (selectedConfig?.storageType === 'local') {
    return '目录名称用于组织文件，支持中文、英文、数字和常见符号'
  }
  return '桶名称必须全局唯一，只能包含小写字母、数字和连字符，长度3-63个字符'
}

// 默认桶开关变化处理
function handleDefaultChange(event) {
  form.isDefault = event.detail.value ? 1 : 0
}


// 表单验证
function validateForm() {
  if (!form.configId) {
    proxy.$modal.showToast('请选择存储配置')
    return false
  }

  if (!form.bucketName) {
    proxy.$modal.showToast('请输入桶名称')
    return false
  }

  // 桶名称验证（非本地存储）
  const selectedConfig = currentConfig.value
  if (selectedConfig?.storageType !== 'local') {
    const bucketNameRegex = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/
    if (!bucketNameRegex.test(form.bucketName)) {
      proxy.$modal.showToast('桶名称只能包含小写字母、数字和连字符，长度3-63个字符')
      return false
    }
  }

  return true
}

// 表单提交
async function handleSubmit() {
  try {
    // 表单验证
    await formRef.value.validate()

    if (mode.value === 'add') {
      // 创建存储桶
      const response = await createBucket({
        configId: form.configId,
        bucketName: form.bucketName
      })

      if (response.code === 200) {
        // 如果设置了权限且不是本地存储，设置权限
        if (currentConfig.value?.storageType !== 'local' && form.permission !== 'private') {
          await setBucketPermission({
            bucketName: form.bucketName,
            permission: form.permission,
            configId: form.configId
          })
        }

        // 如果设置为默认桶
        if (form.isDefault === 1) {
          await handleSetAsDefault()
        }

        proxy.$modal.showToast('创建成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    } else {
      // 编辑模式：更新权限和默认设置
      const tasks = []

      // 更新权限
      if (currentConfig.value?.storageType !== 'local') {
        tasks.push(setBucketPermission({
          bucketName: form.bucketName,
          permission: form.permission,
          configId: form.configId
        }))
      }

      // 设置默认桶
      if (form.isDefault === 1) {
        tasks.push(handleSetAsDefault())
      }

      await Promise.all(tasks)

      proxy.$modal.showToast('保存成功')
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errorFields) {
      proxy.$modal.showToast('请填写必填项')
    } else {
      proxy.$modal.showToast('操作失败')
    }
  }
}

// 设置为默认桶
async function handleSetAsDefault() {
  // 先获取完整的存储配置信息
  const response = await getStorageConfig(form.configId)
  const configData = response.data
  configData.bucketName = form.bucketName

  // 更新存储配置
  return updateStorageConfig(configData)
}

// 取消
function handleCancel() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

.config-info {
  margin-top: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;

  .info-item {
    display: flex;
    margin-bottom: 4px;
    font-size: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      color: #666;
      font-weight: 500;
    }

    .info-value {
      color: #333;
      flex: 1;
    }
  }
}

.local-storage-info {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #f0f8ff;
  border-radius: 6px;
  border: 1px solid #91d5ff;
  margin: 12px 0;

  .info-text {
    margin-left: 8px;
    font-size: 14px;
    color: #666;
    line-height: 1.4;
  }
}

.permission-tips {
  margin-top: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;

  .tip-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 12px;
    line-height: 1.4;

    &:last-child {
      margin-bottom: 0;
    }

    .tip-label {
      color: #333;
      font-weight: 500;
      margin-right: 4px;
    }

    .tip-text {
      color: #666;
      flex: 1;
    }
  }
}

.bucket-info {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #e9ecef;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      font-size: 14px;
      color: #666;
      font-weight: 500;
    }

    .info-value {
      font-size: 14px;
      color: #333;
      text-align: right;
      flex: 1;
      margin-left: 12px;
    }
  }
}

.form-tip {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

// 额外操作按钮样式已移到通用 edit-page.scss 中
</style>